import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'simple_lottery_controller.dart';

class SimpleLotteryWidget extends StatefulWidget {
  final SimpleLotteryController controller;

  SimpleLotteryWidget({Key? key, required this.controller});

  @override
  _SimpleLotteryWidgetState createState() => _SimpleLotteryWidgetState();
}

class _SimpleLotteryWidgetState extends State<SimpleLotteryWidget>
    with TickerProviderStateMixin {
  late Animation<int> _selectedIndexTween;
  late AnimationController _startAnimateController;
  int _currentSelect = -1;
  final int _totalIndex = 8;

  late VoidCallback _listener;
  late List<String> _rewardsList;

  /// 选中下标的映射
  final Map<int, int> _selectIndexMap = const {
    0: 0,
    1: 1,
    2: 2,
    3: 3,
    4: 7,
    5: 6,
    6: 5,
    7: 4
  };

  /// 反向map
  final Map<int, int> _reverseSelectMap = const {
    0: 0,
    1: 1,
    2: 2,
    3: 3,
    7: 4,
    6: 5,
    5: 6,
    4: 7
  };

  _SimpleLotteryWidgetState() {
    _listener = () {
      if (widget.controller.value.isPlaying) {
        _startActualAnimation();
      }
    };
  }

  /// 初始化tween
  Animation<int> _initSelectIndexTween({int begin = 0, int end = 0, Curve curve = Curves.linear}) {
    return StepTween(begin: begin, end: end).animate(
        CurvedAnimation(parent: _startAnimateController, curve: curve));
  }

  _startActualAnimation() {
    _selectedIndexTween = _initSelectIndexTween(
        begin: widget.controller.value.start,
        end: widget.controller.value.repeatRound * _totalIndex +
            widget.controller.value.target,
        curve: Curves.easeOutCubic);
    _startAnimateController
      ..reset()
      ..duration = widget.controller.value.duration
      ..forward();
  }

  @override
  void didUpdateWidget(covariant SimpleLotteryWidget oldWidget) {
    if (oldWidget.controller != widget.controller) {
      _reset(oldWidget);
    }
    super.didUpdateWidget(oldWidget);
  }

  _reset(SimpleLotteryWidget oldWidget) {
    oldWidget.controller.removeListener(_listener);
    widget.controller.addListener(_listener);
    _rewardsList = widget.controller.value.rewardsList;
    _currentSelect = -1;
  }

  @override
  void initState() {
    _startAnimateController = AnimationController(
        vsync: this, duration: widget.controller.value.duration);
    _selectedIndexTween = _initSelectIndexTween(begin: widget.controller.value.start, end: _totalIndex);

    // 动画监听
    _startAnimateController.addListener(() {
      // 更新选中的下标
      _currentSelect = _selectIndexMap[_selectedIndexTween.value % _totalIndex]!;
      if (_startAnimateController.isCompleted) {
        widget.controller.finish();
      }
      setState(() {});
    });

    // 控制监听
    widget.controller.addListener(_listener);
    _rewardsList = widget.controller.value.rewardsList;
    super.initState();
  }

  @override
  void deactivate() {
    widget.controller.removeListener(_listener);
    super.deactivate();
  }

  @override
  void dispose() {
    _startAnimateController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        width: 220,
        height: 220,
        child: GridView.builder(
            itemCount: 8,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4, crossAxisSpacing: 4, mainAxisSpacing: 4),
            itemBuilder: (context, index) {
              return Container(
                child: Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    Image.asset(_rewardsList[_reverseSelectMap[index]!]),
                    Container(
                      width: 50,
                      height: 50,
                      color: index == _currentSelect
                          ? Colors.blue.withOpacity(0.5)
                          : Colors.amber.withOpacity(0.5),
                    ),
                  ],
                ),
              );
            }));
  }
}
